import { Injectable } from '@angular/core';
import { environment } from '../../environments/environment';
import { HttpClient, HttpHeaders, HttpParams, HttpResponse } from '@angular/common/http';
import { BoardVo } from '../model/board-vo';
import { BoardCollectBoardGroupVo } from '../model/board-collect-board-group-vo';
import { BoardStatsVo } from '../model/board-stats-vo';
import { BoardCollectStatsVo } from '../model/board-collect-stats-vo';
import { EMPTY, throwError, Observable } from 'rxjs';
import { EntityPageResult } from '../model/entity-page-result';
import { BoardRecordVo } from '../model/board-record-vo';
import { BoardUnionCheckVo } from '../model/board-union-check-vo';
@Injectable({
  providedIn: 'root'
})
export class BoardService {
  private restRequestURI: string = environment.restURI + '/board';
  /**
   * 版块REST API服务
   */
  constructor(private http: HttpClient) { }
  /**
   * 查看指定的版块
   * @param boardId 版块ID
   */
  public get(boardId: number): Observable<BoardVo> {
    if (0 >= boardId) {
      return throwError('版块ID非可用值');
    }
    return this.http.get<BoardVo>(this.restRequestURI + '/' + boardId);
  }
  /**
   * 查看指定的版块,级联加载版块组
   * @param boardId 版块ID
   * @param boardGroupId 版块组ID
   */
  public getCascade(boardId: number, boardGroupId: number): Observable<BoardCollectBoardGroupVo> {
    if (0 >= boardId || 0 >= boardGroupId) {
      return throwError('版块ID或版块组非可用值');
    }
    return this.http.get<BoardCollectBoardGroupVo>(this.restRequestURI + '/' + boardId + '/volume/' + boardGroupId);
  }
  /**
   * 查看指定版块组下可用的所有版块
   * @param boardGroupId 版块组ID
   */
  public getAllUsed(boardGroupId: number): Observable<BoardVo[]> {
    if (0 >= boardGroupId) {
      return throwError('版块组ID非可用值');
    }
    //:/all/{volume}
    return this.http.get<BoardVo[]>(this.restRequestURI + '/all/' + boardGroupId);
  }
  /**
   * 查看指定版块的统计
   * @param boardId 版块ID
   */
  public getStats(boardId: number): Observable<BoardStatsVo> {
    if (0 >= boardId) {
      return throwError('版块ID非可用值');
    }
    return this.http.get<BoardStatsVo>(this.restRequestURI + '/' + boardId + '/stats');
  }
  /**
   * 查看指定版块的统计
   * @param boardIds 版块ID数组,格式:id1,id2,...idN
   */
  public getMultiStats(boardIds: number[]): Observable<BoardStatsVo[]>{
    if(!boardIds || boardIds.length == 0){
      return throwError('缺少版块ID');
    }
    //:/stats/multi
    const httpOptions = {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    };
    const body = new HttpParams().set('records', boardIds.join());
    return this.http.post<BoardStatsVo[]>(this.restRequestURI + '/stats/multi', body.toString(), httpOptions);
  }
  /**
   * 查看指定会员收藏的版块[并加载版块的统计]
   * @param memberId 会员ID
   * @param showSize 显示的数量,有效范围值在:>1--<10
   */
  public getMemberFavorite(memberId: number, showSize: number = 5): Observable<BoardCollectStatsVo[]> {
    if (0 >= memberId) {
      return throwError('会员ID非可用值');
    }
    //:/favorite/member/{member}
    let ss = 5;
    if (showSize > 10 || showSize < 1) {
      ss = showSize;
    }
    let params = new HttpParams().append('size', ss + '');
    return this.http.get<BoardCollectStatsVo[]>(this.restRequestURI + '/favorite/member/' + memberId, { params: params });
  }
  /**
   * 查看指定会员收藏的版块[并解码版块图标地址]
   * @param memberId 会员ID
   * @param showSize 显示的数量,有效范围值在:>1--<10
   * @param scale 图片的尺寸,若为null表示自动
   */
  public getMemberStar(memberId: number, showSize: number = 5, scale: string): Observable<BoardVo[]> {
    if (0 >= memberId) {
      return throwError('会员ID非可用值');
    }
    //:/favorite/member/{member}
    let ss = 5;
    if (showSize > 10 || showSize < 1) {
      ss = showSize;
    }
    let params = new HttpParams().append('size', ss + '').append('scale', scale);
    return this.http.get<BoardVo[]>(this.restRequestURI + '/star/member/' + memberId, { params: params });
  }
  /**
   * 查看指定的会员是否收藏过指定的版块
   * @deprecated
   * @param boardId 版块ID
   * @param memberId 会员ID
   * @returns 成功200(可以收藏),失败417(已经收藏过了)
   */
  public isFavorited(boardId: number, memberId: number): Observable<string> {
    //:/{id}/favorite/member/{member}
    if (0 >= memberId) {
      return throwError('会员ID非可用值');
    }
    if (0 >= boardId) {
      return throwError('版块ID非可用值');
    }
    const headers = new HttpHeaders().set('Content-Type', 'text/plain; charset=utf-8');
    return this.http.get(this.restRequestURI + '/' + boardId + '/favorite/member/' + memberId, { headers, responseType: 'text' });
  }
    /**
   * 联合检查:
   *  1)是否可以收藏, 可以返回true
   *  
   * @param boardId 版块ID
   * @param memberId 会员ID
   */
  public getSSEUnionCheckResult(boardId: number, memberId: number): Observable<BoardUnionCheckVo> {
    if (0 >= memberId) {
      return throwError('暂不支持游客');
    }
    if (0 >= boardId) {
      return throwError('版块ID非可用值');
    }
    //:/{id}/check/{member}/operate
    const url: string = this.restRequestURI + '/' + boardId + '/check/'+ memberId+'/operate';
    return new Observable<BoardUnionCheckVo>(observer => {
      const eventSource = new EventSource(url);
      eventSource.addEventListener('BoardUnionCheck', (evt: any) => {
        observer.next(JSON.parse(evt.data) as BoardUnionCheckVo);
      });
      
      eventSource.addEventListener('error', (event) => {
        if (event.eventPhase == EventSource.CLOSED) {
          eventSource.close();
          console.log("[unionCheckBoard]REST Event Source Closed");
        }else{
          observer.error(event);
        }

      });
      //关闭了无法继续接受值
      return () => eventSource.close();
    });
  }
  /**
   * 收藏版块
   * @param boardId 版块ID
   * @param memberId 会员ID
   * @param memberNickname 会员昵称
   * @param token 
   * @param ipAddr 
   * @returns 成功的状态码是200,失败的状态:417
   */
  public favorite(boardId: number, memberId: number, memberNickname: string, token: string, ipAddr: string): Observable<HttpResponse<string>> {
    if (0 >= boardId) {
      return throwError('版块ID非可用值');
    }
    if (0 >= memberId) {
      return throwError('暂不支持游客收藏');
    }
    //:/{id}/favorite
    const httpOptions = {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    };
    const body = new HttpParams().set('member', memberId + '').set('nickname', memberNickname).set('token', token).set('ip', ipAddr);
    return this.http.put<HttpResponse<string>>(this.restRequestURI + '/' + boardId + '/favorite', body.toString(), httpOptions);
  }
  /**
   * 查看指定会员收藏的版块操作记录
   * @param memberId 会员ID
   * @param page 
   * @param pageSize 
   */
  public getAllFavorite(memberId: number, page: number = 1, pageSize: number = 20): Observable<EntityPageResult<BoardRecordVo>> {
    if (0 >= memberId) {
      return throwError('会员ID非可用值');
    }
    //:/favorite/member/{member}/{page}/{number}
    return this.http.get<EntityPageResult<BoardRecordVo>>(this.restRequestURI + '/favorite/member/' + memberId + '/' + page + '/' + pageSize);
  }
  /**
   * 删除会员收藏的版块
   * @param boardId 版块ID
   * @param memberId 
   * @param memberNickname 
   * @param token 
   * @param ipAddr 
   */
  public cancelFavorite(boardId: number, memberId: number, memberNickname: string, token: string, ipAddr: string): Observable<HttpResponse<string>> {
    if (0 >= boardId) {
      return throwError('版块ID非可用值');
    }
    if (0 >= memberId) {
      return throwError('会员ID非可用值');
    }
    //:/{id}/favorite
    const httpOptions = {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    };
    const body = new HttpParams().set('member', memberId + '').set('nickname', memberNickname).set('token', token).set('ip', ipAddr);
    return this.http.put<HttpResponse<string>>(this.restRequestURI + '/' + boardId + '/favorite/cancel', body.toString(), httpOptions);
  }
}
